package org.dromara.quick.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.core.utils.IdGenerator;
import org.dromara.quick.chat.domain.ImGroupStatistics;
import org.dromara.quick.chat.mapper.ImGroupStatisticsMapper;
import org.dromara.quick.chat.service.ImGroupStatisticsService;
import org.springframework.stereotype.Service;

/**
* @author Stars
* @description 针对表【im_group_statistics(群统计表，用于记录群聊的各项统计数据)】的数据库操作Service实现
* @createDate 2025-03-04 22:33:21
*/
@Service
public class ImGroupStatisticsServiceImpl extends ServiceImpl<ImGroupStatisticsMapper, ImGroupStatistics>
    implements ImGroupStatisticsService{

    @Override
    public void addUserCount(Long groupId) {
        ImGroupStatistics imGroupStatistics = new ImGroupStatistics();


        // 判断是否存在
        ImGroupStatistics groupStatistics = this.getOne(new LambdaQueryWrapper<ImGroupStatistics>().eq(ImGroupStatistics::getGroupId, groupId));
        if (groupStatistics != null) {
            // 直接从数据库层面添加1，避免解决并发问题
            LambdaUpdateWrapper<ImGroupStatistics> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ImGroupStatistics::getGroupId, groupId)
                .setSql("total_members = total_members + 1");
            baseMapper.update(null, updateWrapper);
            return;
        }
        // 不存在，新增
        imGroupStatistics.setId(IdGenerator.getId());
        imGroupStatistics.setGroupId(groupId);
        imGroupStatistics.setTotalMembers(1);
        imGroupStatistics.setActiveMembers(1);
        this.save(imGroupStatistics);
    }
}




